#!/bin/bash
# add uid to group's memberuid attribute

uid=$1
groupcn=$2
binddn='cn=Manager,dc=jhc,dc=cn'
pwdfile=~/.ldappwd
basedn='dc=jhc,dc=cn'

#groupcn should be unique
(ldapsearch -x -y "$pwdfile" -D "$binddn" -b "$basedn" -s sub "(&(objectClass=posixGroup)(cn=$groupcn))"  | grep '^# numEntries: 1') >/dev/null
if [ $? -ne 0 ] ; then
    echo "$groupcn does not exists or is not unique in server."
    exit 1
fi
#uid should exists
(ldapsearch -x -y "$pwdfile" -D "$binddn" -b "$basedn" -s sub "(uid=$uid)"  | grep '^# numEntries: 1') >/dev/null
if [ $? -ne 0 ] ; then
    echo "$uid is does not exists or or not unique in server."
    exit 1
fi


groupdn=$(ldapsearch -L -o ldif-wrap=no -x -y "$pwdfile" -D "$binddn" -b "$basedn" -s sub "(&(objectClass=posixGroup)(cn=$groupcn))" | grep '^dn:')
# groupdn may be base64 code, depends on line head
(echo -n "$groupdn" | grep '^dn:: ') > /dev/null
if [ $? -eq 0 ] ; then
    groupdn=${groupdn#dn:: }
    groupdn=$(echo -n "$groupdn" | base64 -d)
else
    groupdn=${groupdn#dn: }
fi

#echo "$groupdn"
echo -e -n "dn: $groupdn\nchangetype: modify\nadd: memberUid\nmemberUid: $uid\n" | ldapmodify -x -y "$pwdfile" -D "$binddn"

